package cn.edu.scnu.socialapp.service.impl;

import cn.edu.scnu.socialapp.dao.mapper.CommentMapper;
import cn.edu.scnu.socialapp.model.entity.Comment;
import cn.edu.scnu.socialapp.model.entity.User;
import cn.edu.scnu.socialapp.service.CommentsService;
import cn.edu.scnu.socialapp.service.ThreadService;
import cn.edu.scnu.socialapp.service.UserService;
import cn.edu.scnu.socialapp.utils.UserThreadLocal;
import cn.edu.scnu.socialapp.model.vo.CommentVo;
import cn.edu.scnu.socialapp.model.vo.Result;
import cn.edu.scnu.socialapp.model.vo.params.CommentParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
public class CommentsServiceImpl implements CommentsService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ThreadService threadService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //对list表中的comment进行判断
    public List<CommentVo> copyList(List<Comment> commentList) {
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            commentVoList.add(copy(comment));
        }
        return commentVoList;
    }

    private CommentVo copy(Comment comment) {
        CommentVo commentVo = new CommentVo();
        // 相同属性copy
        BeanUtils.copyProperties(comment, commentVo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(comment.getCreateTime());
        commentVo.setCreateDate(date);
        commentVo.setId(comment.getCommentId());
        //作者信息
        commentVo.setAuthor(userService.findUserVoByUserId(comment.getAuthorId()));
        //子评论
        Integer level = comment.getLevel();
        if (1 == level) {
            Long id = comment.getCommentId();
            List<CommentVo> commentVoList = findCommentsByParentId(id);
            commentVo.setChildren(commentVoList);
        }
        //to User 给谁评论
        if (level > 1) {
            commentVo.setToUser(userService.findUserVoByUserId(comment.getToUid()));
        }
        return commentVo;
    }

    @Override
    public Result commentsByArticleId(Long articleId) {
        /**
         * 1. 根据文章id查询评论列表 从comment表中查询
         * 2. 根据作者的id 查询作者的信息
         * 3. 判断 如果level = 1 要去查询它有没有子评论
         * 4. 如果有 根据评论id 进行查询（parent_id）
         */
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        //根据文章id进行查询
        queryWrapper.eq(Comment::getArticleId, articleId);
        //根据层级关系进行查询
        queryWrapper.eq(Comment::getLevel, 1);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        List<CommentVo> commentVoList = copyList(comments);
        // 保证楼层正确显示
        Collections.reverse(commentVoList);
        return Result.success(commentVoList);
    }

    private List<CommentVo> findCommentsByParentId(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId, id);
        queryWrapper.eq(Comment::getLevel, 2);
        List<Comment> comments = this.commentMapper.selectList(queryWrapper);
        return copyList(comments);
    }

    @Override
    public Result comment(CommentParams commentParams) {
        User user = UserThreadLocal.get();
        Comment comment = new Comment();
        comment.setArticleId(commentParams.getArticleId());
        comment.setContent(commentParams.getContent());
        comment.setAuthorId(user.getUserId());
        comment.setCreateTime(LocalDateTime.now());
        Long parentId = commentParams.getParent();
        if (parentId == null || parentId == 0) {
            comment.setLevel(1);
        } else {
            comment.setLevel(2);
        }
        comment.setParentId(parentId == null ? 0 : parentId);
        Long toUserId = commentParams.getToUserId();
        comment.setToUid(toUserId == null ? 0 : toUserId);
        // 添加评论
        commentMapper.insert(comment);
        // 删除缓存
        deleteCache("*" + DigestUtils.md5Hex(commentParams.getArticleId().toString()));
        // 更新文章评论数
        threadService.updateArticleCommentCount(commentParams.getArticleId());
        return Result.success(null);
    }

    private void deleteCache(String regex) {
        Set<String> keys = redisTemplate.keys(regex);
        redisTemplate.delete(keys);
    }
}
